//
//  CLTools.m
//  touguApp
//
//  Created by 夏成龙 on 16/6/27.
//  Copyright © 2016年 夏成龙. All rights reserved.
//

#import "ECTCLTools.h"
#import <sys/utsname.h>
//#import "ECTMediator+ModuleLogin.h"
//#import "ECTWLaunchViewController.h"
//#import "ECTFinanceWebViewController.h"
//#import "RealNameViewController.h"
//#import "ECTWCustomAlertView.h"
#import "AFNetworking.h"
@interface ECTCLTools()

@property (nonatomic,strong)AFHTTPSessionManager *manager;

@end
@implementation ECTCLTools

+(UIBarButtonItem *)leftBarButtonItem:(UIViewController *)viewController target:(id)target action:(SEL)action{

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 55, 44);
    [button setImage:[[UIImage imageNamed:@"icon_return_red"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, -40, 0, 0);
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    viewController.navigationItem.leftBarButtonItem = leftItem;
    return leftItem;
}

+ (UIBarButtonItem *)barButtonItem:(UIViewController *)viewController title:(NSString *)title selectedTitle:(NSString *)selectedTitle titleColor:(UIColor *)titleColor imageName:(NSString *)imageName selectedImage:(NSString *)selectedImage backgroundImge:(NSString *)backgroundImage selecgedgroundImage:(NSString *)selecgedgroundImage target:(id)target action:(SEL)action{
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 80, 25);
    if (title) {
        [rightBtn setTitle:title forState:UIControlStateNormal];
        [rightBtn setTitleColor:titleColor forState:UIControlStateNormal];
        rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        //        NSLog(@"%@",[UIFont familyNames]);
        //        NSLog(@"%@",[UIFont fontNamesForFamilyName:@"Copperplate"]);
    }
    rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;

    
    if (selectedTitle) {
        [rightBtn setTitle:selectedTitle forState:UIControlStateSelected];
        [rightBtn setTitleColor:titleColor forState:UIControlStateSelected];
    }
    if (imageName) {
        [rightBtn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    if (selectedImage) {
        [rightBtn setImage:[UIImage imageNamed:selectedImage] forState:UIControlStateSelected];
    }
    if (backgroundImage) {
        [rightBtn setBackgroundImage:[UIImage imageNamed:backgroundImage] forState:UIControlStateNormal];
    }
    if (selecgedgroundImage) {
        [rightBtn setBackgroundImage:[UIImage imageNamed:selecgedgroundImage] forState:UIControlStateSelected];
    }
    [rightBtn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    return [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
}

+ (UIButton *)buttonTitle :(NSString *)title frame:(CGRect)frame font:(NSInteger)font titleColor:(UIColor *)titleColor imageName:(id)imageName backgroundImage:(id)backgroundImage target:(id)target action:(SEL)action superView:(UIView *)superView constraintMaker:(void (^)(MASConstraintMaker *))make
{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    UIFont *labelFont = [UIFont systemFontOfSize:font];
    button.titleLabel.font = labelFont;
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    if (title) {
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:titleColor forState:UIControlStateNormal];
    }
    
    if (imageName && [imageName isKindOfClass:[NSString class]]) {
        [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    
    if (imageName && [imageName isKindOfClass:[UIImage class]]) {
        [button setImage:imageName forState:UIControlStateNormal];
    }
    
    
    if (backgroundImage && [backgroundImage isKindOfClass:[NSString class]]) {
        [button setBackgroundImage:[UIImage imageNamed:backgroundImage] forState:UIControlStateNormal];
    }
    if (backgroundImage && [backgroundImage isKindOfClass:[UIImage class]]) {
        [button setBackgroundImage:backgroundImage forState:UIControlStateNormal];
    }
    
    if (target && action) {
        [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    if (superView) {
        [superView addSubview:button];
    }else{
        return button;
    }
    //布局
    if (make) {
        [button mas_makeConstraints:make];
    }
    return button;
}

+ (UILabel *)labelWithTitle:(NSString *)title titleColor:(UIColor *)titleColor font:(CGFloat)font frame:(CGRect)frame superView:(UIView *)superView constraintMaker:(void (^)(MASConstraintMaker *))make{
    
    UILabel *label = [[UILabel alloc]initWithFrame:frame];
    label.textColor = titleColor;
    label.text = title;
    label.font = [UIFont systemFontOfSize:font];
    if (superView) {
        [superView addSubview:label];
    }else{
        return label;
    }
    if (make) {
        [label mas_makeConstraints:make];
    }
    return label;
}

+ (UIImageView *)imageViewWithImageName:(NSString *)imageName frame:(CGRect)frame superView:(UIView *)superView constraintMaker:(void (^)(MASConstraintMaker *make))make{
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:frame];
    if (imageName) {
        imageView.image = [UIImage imageNamed:imageName];
    }
    if (superView) {
        [superView addSubview:imageView];
    }else{
        return imageView;
    }
    if (make) {
        [imageView mas_makeConstraints:make];
    }
    return imageView;
}
+ (UIView *)viewWithBackgroundColor:(UIColor *)backgroundColor frame:(CGRect)frame superView:(UIView *)superView constraintMaker:(void (^)(MASConstraintMaker *))make{
    UIView *view = [[UIView alloc]initWithFrame:frame];
    view.backgroundColor = backgroundColor;
    if (superView) {
        [superView addSubview:view];
    }else{
        return view;
    }
    if (make) {
        [view mas_makeConstraints:make];
    }
    return view;
}

+ (UIImage *)imageWithColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
//通过字符串获得图片
+ (UIImage *)imageFromText:(NSString *)text withAttribute:(NSDictionary *)attribute font:(CGFloat)fontSize maxWidth:(CGFloat)maxWidth {
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    NSNumber *kern = attribute[NSKernAttributeName] ? attribute[NSKernAttributeName] : @0;
    CGSize textSize = [text boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font,NSKernAttributeName:kern} context:nil].size;
    UIGraphicsBeginImageContextWithOptions(textSize, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetTextDrawingMode(context, kCGTextFill);
    
    NSMutableDictionary *attr = [NSMutableDictionary dictionaryWithDictionary:attribute];
    if (!attr[NSKernAttributeName]) {
        attr[NSKernAttributeName] = kern;
    }
    if (!attribute[NSForegroundColorAttributeName]) {
        attr[NSForegroundColorAttributeName] = [UIColor blackColor];
    }
    attr[NSFontAttributeName] = font;
    [text drawInRect:CGRectMake(0, 0, textSize.width, textSize.height) withAttributes:attr];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


+ (BOOL)writeDataToCacheWithData:(NSDictionary *)dataDict identifier:(NSString *)identifier currentClass:(Class)currentClass
{
    if (dataDict == nil) return NO;
    
    NSString *pathStr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSFileManager *fm = [NSFileManager defaultManager];
    
    pathStr = [pathStr stringByAppendingPathComponent:NSStringFromClass(currentClass)];
    
    [fm createDirectoryAtPath:pathStr  withIntermediateDirectories:YES attributes:nil error:nil];
    
    pathStr = [pathStr stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",identifier]];
    
    NSData *data = [NSJSONSerialization dataWithJSONObject:dataDict options:NSJSONWritingPrettyPrinted error:nil];
    
    return [data writeToFile:pathStr atomically:YES];
}

+ (NSDictionary *)readDataFromCacheWithIdentifier:(NSString *)identifier currentClass:(Class)currentClass{
    
    NSString *pathStr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    //路径
    pathStr = [pathStr stringByAppendingPathComponent:NSStringFromClass(currentClass)];
    //    [fm createDirectoryAtPath:pathStr  withIntermediateDirectories:YES attributes:nil error:nil];
    
    pathStr = [pathStr stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",identifier]];
    
    NSData *data = [NSData dataWithContentsOfFile:pathStr];
    //    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    //
    //    NSLog(@"%@",str);
    NSDictionary *dict = nil;
    if (data) {
        dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    }
    return dict;
}

//删除缓存数据
+ (BOOL)removeDataToCacheWithIdentifier:(NSString *)identifier currentClass:(Class)currentClass{
    
    NSString *pathStr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    
    NSFileManager *fm = [NSFileManager defaultManager];
    //路径
    pathStr = [pathStr stringByAppendingPathComponent:NSStringFromClass(currentClass)];
    pathStr = [pathStr stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",identifier]];
    
    if ([fm fileExistsAtPath:pathStr]) {//有该文件的存在
        BOOL result = [fm removeItemAtPath:pathStr error:nil];
        return result;
    }
    return YES;
    
}

+ (void)getRequestWithPath:(NSString *)path parms:(NSDictionary *)parms success:(void (^)(NSDictionary *response))success fail:(void (^)(NSError *fail))fail{
    
    
    AFHTTPSessionManager *manager = [self shareManager];
    [manager GET:path parameters:parms progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}

+ (void)postRequestWithPath:(NSString *)path parms:(NSDictionary *)parms success:(void (^)(NSDictionary *response))success fail:(void (^)(NSError *fail))fail{
    
    AFHTTPSessionManager *manager = [self shareManager];
    [manager POST:path parameters:parms progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
    
}

+ (void)getRequestWithImcPath:(NSString *)path parms:(NSDictionary *)parms success:(void (^)(NSDictionary *))success fail:(void (^)(NSError *))fail{
    
    AFHTTPSessionManager *manager = [self shareManager];
    manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://11.8.37.60:8080/iap/"]];
    
    [manager GET:path parameters:parms progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success((NSDictionary *)responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}

+ (void)postRequestWithImcPath:(NSString *)path parms:(NSDictionary *)parms success:(void (^)(NSDictionary *response))success fail:(void (^)(NSError *fail))fail{
    
    AFHTTPSessionManager *manager = [self shareManager];
    manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://11.8.37.60:8080/iap/"]];
    
    [manager POST:path parameters:parms progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
    
}


+(AFHTTPSessionManager *)shareManager{
    
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
//        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://11.8.37.60:8080/iap/imc"]];
        manager = [[AFHTTPSessionManager alloc] init];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
//        [manager.requestSerializer setValue:[BaseNetworkBL currentUserunDecodeUserId] forHTTPHeaderField:@"userId"];
        
        NSDictionary *infoDictionary = [NSBundle mainBundle].infoDictionary;
        NSString *currentVersion = infoDictionary[@"CFBundleShortVersionString"];
        [manager.requestSerializer setValue:currentVersion forHTTPHeaderField:@"bbVersion"];
        [manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"osType"];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json",@"text/html",nil];
    });
    
    return manager;
}


+ (void)cancelAllManager{
    //取消下载
    [[self shareManager].operationQueue cancelAllOperations];
}




//+(NSMutableAttributedString *)getArributStringFormString:(NSString *)string withTargetStrin:(NSString *)targetString{
//
//    NSMutableArray *mArray = nil;
//    if ([targetString containsString:@" "]){
//        NSArray *array = [targetString componentsSeparatedByString:@" "];
//        mArray = [NSMutableArray arrayWithArray:array];
//
//        for (int i = 0; i < array.count; i ++) {
//            NSString *str = array[i];
//            if ([str isEqualToString:@" "]) {
//                [mArray removeObject:str];
//            }
//        }
//    }else{
//        mArray = [NSMutableArray arrayWithObject:targetString];
//    }
//
//    return nil;
//}




+ (NSMutableAttributedString *)getAttributeStingWithTargetContentTextString:(NSString *)textStrng tagArray:(NSArray *)tagArray atrributDict:(NSDictionary *)attributeDict
{
    
    if (textStrng == nil) {
        textStrng = @"";
    }
    
    if (attributeDict == nil) {
        attributeDict = @{NSForegroundColorAttributeName: [UIColor colorWithRed:1.0 green:86 / 255.0 blue:86 / 255.0  alpha:1.0]};
    }
    
    NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc]initWithString:textStrng];
    
    //分割要搜索的文字
    //    NSArray *tagArray = [tagString componentsSeparatedByString:@" "];
    //    NSMutableArray *mTagArray = [NSMutableArray arrayWithArray:tagArray];
    //
    //    for (int i = 0; i < tagArray.count; i ++) {
    //        NSString *str = tagArray[i];
    //        if ([str isEqualToString:@""]) {
    //            [mTagArray removeObject:str];
    //        }
    //
    //    }
    
    for (NSString *matchStr in tagArray) {//匹配要查找的文字
        
        NSError *error = NULL;
        NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:matchStr
                                                                             options:NSRegularExpressionCaseInsensitive
                                                                               error:&error];
        NSArray *match = [reg matchesInString:textStrng options:NSMatchingReportCompletion range:NSMakeRange(0, [textStrng length])];
        
        // 取得所有的NSRange对象
        if(match.count != 0) //获得富文本
        {
            for (NSTextCheckingResult *matc in match)
            {
                NSRange range = [matc range];
                [attriStr addAttributes:attributeDict range:range];
            }
        }
    }
    return attriStr;
}


/**
 * 根据时间戳获得时间
 */
+ (NSString *)getTimeStrWithDate:(NSInteger)date{
    
    NSString *timeString = nil;
    
    NSDate *lastDate = [NSDate dateWithTimeIntervalSince1970:date];
    
    // 1.获得年月日
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour |NSCalendarUnitMinute;
    NSDateComponents *cmp1 = [calendar components:unitFlags fromDate:lastDate];
    NSDateComponents *cmp2 = [calendar components:unitFlags fromDate:[NSDate date]];
    
    // 2.格式化日期
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if ([cmp1 day] == [cmp2 day]) { // 今天
        formatter.dateFormat = @"HH:mm";
    }else if ([cmp1 day] + 1 == [cmp2 day]){
        formatter.dateFormat = @"昨天";
    }
    else if ([cmp1 year] == [cmp2 year]) { // 今年
        formatter.dateFormat = @"MM-dd";
    } else {
        formatter.dateFormat = @"yyyy-MM-dd";
    }
    timeString = [formatter stringFromDate:lastDate];
    return timeString;
}



/**
 * 判断用户是否登录,并进行登录成功的回调
 */
//+ (BOOL)pushViewControllerVerifyLoginCallbackBlock:(void (^)())callbackBlock {
//    if ([BaseNetworkBL currentUser] && [BaseNetworkBL currentUserunDecodeUserId]) {
//        if (callbackBlock) {
//            callbackBlock();//登录成功
//        }
//        return YES;
//    }
//   UIViewController *loginVC = [[ECTMediator alloc] loginViewControllerWithSucceedLoginBlock:^{
//       if (callbackBlock) {
//          callbackBlock();//登录成功
//       }
//   }];
//    ECTWLaunchViewController *lunchVC = (ECTWLaunchViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//    CardNavigationController *currentNav = lunchVC.tabBarVC.selectedViewController;
//    CardNavigationController *nav = [[CardNavigationController alloc] initWithRootViewController:loginVC];
//    [currentNav presentViewController:nav animated:YES completion:nil];
//    return NO;
//}



//获得价格字符串
+ (NSString *)getPriceStringWithPrice:(CGFloat)price{
    
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
    
    NSDecimalNumber * roundedOunces = [[NSDecimalNumber alloc] initWithFloat:price];
    roundedOunces = [roundedOunces decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    return  [NSString stringWithFormat:@"%@",roundedOunces];
}

//价格显示到小数点后两位，末尾0不显示，传过来的是%.2f的字符串
+ (NSString *)convertWithPriceStr:(NSString *)priceStr
{
    NSString *finalPriceStr;
    NSArray *array = [priceStr componentsSeparatedByString:@"."];
    NSString *pointRightStr = array[1];
    int pointRightFirst = [[pointRightStr substringWithRange:NSMakeRange(0, 1)] intValue];
    int pointRightSecond = [[pointRightStr substringWithRange:NSMakeRange(1, 1)] intValue];
    if (pointRightFirst == 0 && pointRightSecond == 0)
    {
        finalPriceStr = array[0];
    }
    else if ((pointRightFirst == 0 && pointRightSecond != 0) || (pointRightFirst != 0 && pointRightSecond != 0))
    {
        finalPriceStr = priceStr;
    }
    else if (pointRightFirst != 0 && pointRightSecond == 0)
    {
        pointRightStr = [NSString stringWithFormat:@"%d",pointRightFirst];
        finalPriceStr = [NSString stringWithFormat:@"%@.%@",array[0],pointRightStr];
    }
    return finalPriceStr;
}


//获得金额
+ (NSString *)getMoneyFormatString:(NSString *)moneyString perString:(NSString *)perString {
    if (moneyString.length == 0) {
        return moneyString;
    }
    NSString *floatString = nil;
    if ([moneyString containsString:@"."]) {
        NSRange range = [moneyString rangeOfString:@"."];
        floatString = [moneyString substringFromIndex:range.location];
        moneyString = [moneyString substringToIndex:range.location];
    }
    
    if (moneyString.length <= 4) {
        if (perString == nil) {
             return [NSString stringWithFormat:@"%@%@", moneyString, floatString ? floatString : @""];
        }
        return [NSString stringWithFormat:@"%@%@%@", perString, moneyString,floatString ? floatString : @""];
    } else {
        NSInteger length = moneyString.length;
        NSMutableString *mStr = [[NSMutableString alloc] initWithString:moneyString];
        for (int i = 1; i < length; i ++) {
            if (i % 3 == 0) {
                [mStr insertString:@"," atIndex:length - i];
            }
        }
        [mStr appendString:floatString ? floatString : @""];
        return mStr;
    }
}

/**
+ (void)ect_application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    
    NSRange range = [url.absoluteString rangeOfString:@"?"];
    NSDictionary *pathDict = [NSMutableDictionary dictionary];
    if (range.location != NSNotFound) {
        NSString *pathStr = [url.absoluteString substringFromIndex:range.location + 1];
        NSArray *paramArray = [pathStr componentsSeparatedByString:@"&"];
        for (NSString *paramStr in paramArray) {
            NSArray *param = [paramStr componentsSeparatedByString:@"="];
            [pathDict setValue:param.lastObject forKey:param.firstObject];
        }
    }
    
    if (pathDict.allKeys.count == 0) return;
    
//    NSLog(@"%@  %@",url.host,url.password);
    if ([url.host isEqualToString:@"stockDetail"]) {
        
        TKHqStockInfo *stcokInfo = [[TKHqStockInfo alloc]init];
        stcokInfo.stockCode = pathDict[@"stockCode"];
        stcokInfo.stockName = pathDict[@"stockName"];
        stcokInfo.market = pathDict[@"stockMarket"];
        stcokInfo.type = pathDict[@"stockType"];
        stcokInfo.offTheField = pathDict[@"fundInOrOut"];
        stcokInfo.investmentTargets = pathDict[@"fundOutIndex"];
        stcokInfo.fundAttribute = pathDict[@"fundInIndex"];
        stcokInfo.subscriptionStatus = pathDict[@"fundNewOrOld"];
        
        ECTWLaunchViewController *lanchVC = (ECTWLaunchViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        UINavigationController *nav = lanchVC.tabBarVC.selectedViewController;
        
//        UIAlertView *al = [[UIAlertView alloc]initWithTitle:@"弹框" message:[NSString stringWithFormat:@"%@",nav] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
//        
//        [al show];
        if ([TKHqStockHelper typeIsInFund:stcokInfo.type]) {//基金
//            if ([TKHqFundHelper fundIsNewDevelopmentWith:stcokInfo]) {//新发基金
//                TKHqNewDevelopmentFundViewController *detailViewCtl=[[TKHqNewDevelopmentFundViewController alloc]initPriceData:stcokInfo];
//                [detailViewCtl setHidesBottomBarWhenPushed:YES];
//                [nav pushViewController:detailViewCtl animated:NO];
//            }else{//基金
                TKHqFundDetailViewController *detailViewCtl=[[TKHqFundDetailViewController alloc]initPriceData:stcokInfo];
                [detailViewCtl setHidesBottomBarWhenPushed:YES];
                [nav pushViewController:detailViewCtl animated:NO];
//            }
        }else{//股票
            TKHqDetailViewController *detailViewCtl=[[TKHqDetailViewController alloc] initPriceData:stcokInfo];
            [detailViewCtl setHidesBottomBarWhenPushed:YES];
            [nav pushViewController:detailViewCtl animated:NO];
        }
    }
}

+ (UIViewController *)ect_viewControllerWithapplication:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options vcBlock:(void (^)(UIViewController *))vcBlock{
    
    NSRange range = [url.absoluteString rangeOfString:@"?"];
    NSDictionary *pathDict = [NSMutableDictionary dictionary];
    if (range.location != NSNotFound) {
        NSString *pathStr = [url.absoluteString substringFromIndex:range.location + 1];
        NSArray *paramArray = [pathStr componentsSeparatedByString:@"&"];
        for (NSString *paramStr in paramArray) {
            NSArray *param = [paramStr componentsSeparatedByString:@"="];
            [pathDict setValue:param.lastObject forKey:param.firstObject];
        }
    }
    
//    if (pathDict.allKeys.count == 0) return nil;
    
//    NSLog(@"%@  %@",url.host,url.password);
    if ([url.host isEqualToString:@"stockDetail"]) {
        
        TKHqStockInfo *stcokInfo = [[TKHqStockInfo alloc]init];
        stcokInfo.stockCode = pathDict[@"stockCode"];
        stcokInfo.stockName = [(NSString *)pathDict[@"stockName"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        stcokInfo.market = pathDict[@"stockMarket"];
        stcokInfo.type = pathDict[@"stockType"];
        stcokInfo.offTheField = [pathDict[@"fundInOrOut"] intValue];
        stcokInfo.investmentTargets = [pathDict[@"fundOutIndex"] intValue];
        stcokInfo.fundAttribute = [pathDict[@"fundInIndex"] intValue];
        stcokInfo.subscriptionStatus = [pathDict[@"fundNewOrOld"] intValue];
 
        if ([TKHqStockHelper typeIsInFund:stcokInfo.type]) {//基金
            if ([TKHqFundHelper fundIsNewDevelopmentWith:stcokInfo]) {//新发基金
                TKHqNewDevelopmentFundViewController *detailViewCtl=[[TKHqNewDevelopmentFundViewController alloc]initPriceData:stcokInfo];
                [detailViewCtl setHidesBottomBarWhenPushed:YES];
                return detailViewCtl;
                
            }else{//基金
                TKHqFundDetailViewController *detailViewCtl=[[TKHqFundDetailViewController alloc]initPriceData:stcokInfo];
                [detailViewCtl setHidesBottomBarWhenPushed:YES];
                detailViewCtl.isOpenUrl = YES;
                return  detailViewCtl;
            }
        }else{//股票
            TKHqDetailViewController *detailViewCtl=[[TKHqDetailViewController alloc] initPriceData:stcokInfo];
            [detailViewCtl setHidesBottomBarWhenPushed:YES];
            return detailViewCtl;
        }
        
    } else if ([url.host isEqualToString:@"qaPage"]){//问答
//        
//        ECTNetworkRequest *request = [ECTNetworkRequest getQADetailRequestWithParams:@{@"userId":mAvailableString([BaseNetworkBL currentUserunDecodeUserId]), @"questionId":pathDict[@"questionId"]}];
//        [[ECTNetworkManager manager] sendMessageWithRequest:request withSucceedBlock:^(NSDictionary *response) {
//            
//            NSLog(@"应答%@", response);

//            [self dealPushData:response block:vcBlock];
//            [self dealPushData:response vcBolck:vcBlock type:ECTWAnswerQuestionPageTypeNormal];
        ECTQuestionAnswerDetailViewController *consultantVC = [[ECTQuestionAnswerDetailViewController alloc]initWithAnswerPageType:ECTWAnswerQuestionPageTypeNormal];
        consultantVC.questionId = pathDict[@"questionId"];
        return consultantVC;
//            
//        } withError:^(NSError *error) {
//
//    
//        }];
//        
    } else if ([url.host isEqualToString:@"cmPage"]){//私人订制
    
//        ECTNetworkRequest *request = [ECTNetworkRequest getPersonalTailorDetailRequestWithParams:@{@"userId":mAvailableString([BaseNetworkBL currentUserunDecodeUserId]), @"questionId":pathDict[@"questionId"]}];//[NSNumber numberWithLong:47091641618432]
//        [[ECTNetworkManager manager] sendMessageWithRequest:request withSucceedBlock:^(NSDictionary *response) {
//
//            NSLog(@"应答%@", response);
//            [self dealPushData:response vcBolck:vcBlock type:ECTWAnswerQuestionPageTypeCustom];
//            
//        } withError:^(NSError *error) {
//            
//        }];
        
        ECTPrivateCustomAnswerDetailViewController *questionDetailForCustomerVC = [[ECTPrivateCustomAnswerDetailViewController alloc] initWithAnswerPageType:ECTWAnswerQuestionPageTypeCustom];
        //问题的参数
        questionDetailForCustomerVC.questionId = pathDict[@"questionId"];
        return questionDetailForCustomerVC;
    } else if ([url.host isEqualToString:@"userPageHome"]){//个人主页
        ECTWPersonalHomePageViewController *personalVC = [[ECTWPersonalHomePageViewController alloc] init];
        //问题的参数
        personalVC.userId = pathDict[@"userId"];
        return personalVC;
    } else if ([url.host isEqualToString:@"makeCommentPage"]){//评论
        ECTOpiniontCommentViewController *commentVC = [[ECTOpiniontCommentViewController alloc] init];
        //问题的参数
        commentVC.opinionId = [NSNumber numberWithUnsignedLongLong:[pathDict[@"opinionId"] longLongValue]];
        return commentVC;
    } else if ([url.host isEqualToString:@"floorPage"]){//回复
        ECTOpinionReplyViewController *replyVC = [[ECTOpinionReplyViewController alloc] init];
        //问题的参数
        replyVC.commentId = pathDict[@"commentId"];
        replyVC.title = pathDict[@"floorTitle"];
        replyVC.becomeFirstResponder = [pathDict[@"reply"] boolValue];
        return replyVC;
    } else if ([url.host isEqualToString:@"opinionPage"]){//观点详情页
        ECTOpinionDetailViewController *opinionDetailVC = [[ECTOpinionDetailViewController alloc] init];
        NSString *opinionId = pathDict[@"opinionId"];
       NSString *urlStr = [NSString stringWithFormat:@"%@/html/issueshare/issuedetail.html?opinionId=%@",[MMutil gatewayHost],opinionId];
//        urlStr = [urlStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        NSMutableString *outputStr = [NSMutableString stringWithString:urlStr];
//        [outputStr replaceOccurrencesOfString:@"+" withString:@" " options:NSLiteralSearch range:NSMakeRange(0, [outputStr length])];
//        NSString *urlStr2 = [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        
        opinionDetailVC.upUrl = urlStr;
        return opinionDetailVC;
    } else if ([url.host isEqualToString:@"finance"]){
        NSString *urlPath = [pathDict objectForKey:@"startpage"];
        urlPath = [urlPath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
        NSString *encodedString = [urlPath stringByAddingPercentEncodingWithAllowedCharacters:set];
        NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:encodedString,@"startPage", nil];
        HybridScreenViewController *hybridVC = [[HybridScreenViewController alloc]initWithData:dic];
        return hybridVC;
    } else if ([url.host isEqualToString:@"openWebView"]) {
        AdWebViewController *webVC = [[AdWebViewController alloc] init];
        NSString *urlStr = [pathDict objectForKey:@"url"];
        urlStr = [urlStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        webVC.upUrl = urlStr;
        return webVC;
    } else if ([url.host isEqualToString:@"ztbHomePage"]) {
       return [self ect_pushIntoZTB];
    }
    
    return nil;
}

+ (UIViewController *)ect_pushIntoZTB {
    if (![BaseNetworkBL currentUser] || ![BaseNetworkBL currentUserunDecodeUserId]) {
        UIViewController *loginVC = [[ECTMediator sharedInstance] loginViewControllerWithSucceedLoginBlock:nil];
        return loginVC;
    }
    
    NSString *isSetPayPwd = [BaseNetworkBL currentUser].isSetPayPwd;
    NSString *isApprove = [BaseNetworkBL currentUser].isApprove;
    
    if (isSetPayPwd && [isSetPayPwd isEqualToString:@"1"]) {
        if (isApprove && [isApprove isEqualToString:@"1"]) {
            ECTBaoHomeViewController *baoHomeVC = [[UIStoryboard storyboardWithName:@"ZhengTongBao"
                                                                             bundle:nil]
                                                   instantiateViewControllerWithIdentifier:@"baoHomeViewControllerIdentifier"];
            return baoHomeVC;
        } else {
            BankBindingViewController *bankBindingVC = [[BankBindingViewController alloc] init];
            bankBindingVC.isFromBao = YES;
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:bankBindingVC];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"BindingCardFromBao"];
            
            UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
            [rootVC presentViewController:navigationController animated:YES completion:nil];
            return nil;
        }
        
    } else {
        ECTWSettingPayPasswordViewController *settingPayPasswordVC = [[ECTWSettingPayPasswordViewController alloc] init];
        settingPayPasswordVC.navigationTitle = @"设置支付密码";
        settingPayPasswordVC.upperLabelText = @"请输入新的支付密码";
        settingPayPasswordVC.lowerLabelText = @"请输入6位非连续且不相同的数字";
        UINavigationController *navigationController = [[UINavigationController alloc]initWithRootViewController:settingPayPasswordVC];
         UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
        [rootVC presentViewController:navigationController animated:YES completion:nil];
        return nil;
    }
    
}

*/
/**
+ (void)dealPushData:(NSDictionary *)response vcBolck:(void (^)(UIViewController *))vcBlock type:(ECTWAnswerQuestionPageType)type{
    
    if (type == ECTWAnswerQuestionPageTypeNormal) {//是顾问看顾问的
    
        ECTQuestionAnswerDetailViewController *consultantVC = [[ECTQuestionAnswerDetailViewController alloc]initWithAnswerPageType:type];
        consultantVC.questionId = response[@"content"][@"questionId"];
        vcBlock(consultantVC);
    } else if (type == ECTWAnswerQuestionPageTypeCustom){
        ECTPrivateCustomAnswerDetailViewController *questionDetailForCustomerVC = [[ECTPrivateCustomAnswerDetailViewController alloc] initWithAnswerPageType:type];
        //问题的参数
        questionDetailForCustomerVC.questionId = response[@"content"][@"questionId"];
        vcBlock(questionDetailForCustomerVC);
    }
}
 */
+ (iphoneType)getIphoneType{
    
    struct utsname systemInfo;
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return iphoneType2G;
    
    if ([platform isEqualToString:@"iPhone1,2"]) return iphoneType3G;
    
    if ([platform isEqualToString:@"iPhone2,1"]) return iphoneType3GS;
    
    if ([platform isEqualToString:@"iPhone3,1"]) return iphoneType4;
    
    if ([platform isEqualToString:@"iPhone3,2"]) return iphoneType4;
    
    if ([platform isEqualToString:@"iPhone3,3"]) return iphoneType4;
    
    if ([platform isEqualToString:@"iPhone4,1"]) return iphoneType4s;
    
    if ([platform isEqualToString:@"iPhone5,1"]) return iphoneType5;
    
    if ([platform isEqualToString:@"iPhone5,2"]) return iphoneType5;
    
    if ([platform isEqualToString:@"iPhone5,3"]) return iphoneType5c;
    
    if ([platform isEqualToString:@"iPhone5,4"]) return iphoneType5c;
    
    if ([platform isEqualToString:@"iPhone6,1"]) return iphoneType5s;
    
    if ([platform isEqualToString:@"iPhone6,2"]) return iphoneType5s;
    
    if ([platform isEqualToString:@"iPhone7,1"]) return iphoneType6sPlus;
    
    if ([platform isEqualToString:@"iPhone7,2"]) return iphoneType6;
    
    if ([platform isEqualToString:@"iPhone8,1"]) return iphoneType6s;
    
    if ([platform isEqualToString:@"iPhone8,2"]) return iphoneType6sPlus;
    
    if ([platform isEqualToString:@"iPhone8,4"]) return iphoneTypeSE;
    
    if ([platform isEqualToString:@"iPhone9,1"]) return iphoneType7;
    
    if ([platform isEqualToString:@"iPhone9,2"]) return iphoneType7Plus;
    
//    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G";
//    
//    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G";
//    
//    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G";
//    
//    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G";
//    
//    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G";
//    
//    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G";
//    
//    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2";
//    
//    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2";
//    
//    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2";
//    
//    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2";
//    
//    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G";
//    
//    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G";
//    
//    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G";
//    
//    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3";
//    
//    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3";
//    
//    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3";
//    
//    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4";
//    
//    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4";
//    
//    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4";
//    
//    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air";
//    
//    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air";
//    
//    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air";
//    
//    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G";
//    
//    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G";
//    
//    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G";
//    
//    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
//    
//    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    
    return platform;
}


/*
 通过色值字符串获得颜色
 */
+ (UIColor *)getColorFromString:(NSString *)cString {
        if ([cString length] < 6) {
            return [UIColor clearColor];
        }
        
        // strip 0X if it appears
        if ([cString hasPrefix:@"0X"]) {
            cString = [cString substringFromIndex:2];
        }
        if ([cString hasPrefix:@"#"]) {
            cString = [cString substringFromIndex:1];
        }
        if ([cString length] != 6) {
            return [UIColor clearColor];
        }
        //r
        NSString *rString = [cString substringWithRange:NSMakeRange(0, 2)];
        //g
        NSString *gString = [cString substringWithRange:NSMakeRange(2, 2)];
        //b
        NSString *bString = [cString substringWithRange:NSMakeRange(4, 2)];
        
        // Scan values
        unsigned int r, g, b;
        [[NSScanner scannerWithString:rString] scanHexInt:&r];
        [[NSScanner scannerWithString:gString] scanHexInt:&g];
        [[NSScanner scannerWithString:bString] scanHexInt:&b];
        return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
@end
